#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
登录对话框模块 - 用于连接Zabbix API的登录界面
"""

import logging
from typing import Dict, Any
from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
    QLineEdit, QPushButton, QFormLayout, QDialogButtonBox,
    QCheckBox
)
from PyQt5.QtCore import Qt

logger = logging.getLogger(__name__)

class LoginDialog(QDialog):
    """Zabbix API登录对话框"""
    
    def __init__(self, config: Dict[str, Any], parent=None):
        """
        初始化登录对话框
        
        Args:
            config (Dict[str, Any]): 应用配置
            parent: 父窗口
        """
        super().__init__(parent)
        self.config = config
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI界面"""
        self.setWindowTitle("登录到Zabbix API")
        self.setFixedWidth(400)
        self.setModal(True)
        
        # 创建主布局
        main_layout = QVBoxLayout(self)
        
        # 创建表单布局
        form_layout = QFormLayout()
        
        # URL输入框
        self.url_edit = QLineEdit()
        self.url_edit.setText(self.config["zabbix_api"]["url"])
        form_layout.addRow("API URL:", self.url_edit)
        
        # 用户名输入框
        self.user_edit = QLineEdit()
        self.user_edit.setText(self.config["zabbix_api"]["user"])
        form_layout.addRow("用户名:", self.user_edit)
        
        # 密码输入框
        self.password_edit = QLineEdit()
        self.password_edit.setEchoMode(QLineEdit.Password)
        
        # 如果配置中存在保存的密码，则设置密码
        saved_password = self.config["zabbix_api"].get("password", "")
        if saved_password:
            self.password_edit.setText(saved_password)
            
        form_layout.addRow("密码:", self.password_edit)
        
        # 记住密码复选框
        self.remember_checkbox = QCheckBox("记住密码")
        
        # 如果配置中有密码，则默认勾选"记住密码"
        if saved_password:
            self.remember_checkbox.setChecked(True)
        else:
            self.remember_checkbox.setChecked(False)
            
        form_layout.addRow("", self.remember_checkbox)
        
        # 添加表单布局到主布局
        main_layout.addLayout(form_layout)
        
        # 添加按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        main_layout.addWidget(button_box)
        
        # 设置对话框属性
        self.setLayout(main_layout)
    
    def accept(self):
        """处理确认按钮点击"""
        # 更新配置
        self.config["zabbix_api"]["url"] = self.url_edit.text()
        self.config["zabbix_api"]["user"] = self.user_edit.text()

        # 根据记住密码选项决定是否保存密码
        if self.remember_checkbox.isChecked():
            # 直接以明文保存密码，不再加密
            self.config["zabbix_api"]["password"] = self.password_edit.text()
            logger.info("密码已保存为明文（按用户要求）")
        else:
            self.config["zabbix_api"]["password"] = ""

        super().accept() 